package models

import (
	"fmt"
	"regexp"
	"time"
)

// OrderType 订单类型枚举
type OrderType string

const (
	OrderTypeLimit  OrderType = "Limit"
	OrderTypeMarket OrderType = "Market"
)

// Order 订单结构
type Order struct {
	OrderID        string    `json:"orderId" validate:"required"`
	Type           OrderType `json:"type" validate:"required,oneof=Limit Market"`
	Currency       string    `json:"currency" validate:"required,len=3"`
	Symbol         string    `json:"symbol" validate:"required"`
	NotionalAmount float64   `json:"notionalAmount" validate:"required,gt=0"`
	Destination    string    `json:"destination" validate:"required"`
	ClientID       string    `json:"clientId" validate:"required"`
	Weight         float64   `json:"weight" validate:"required,gte=0,lte=1"`
	ChildOrders    []Order   `json:"childOrders,omitempty"`
}

// IsBasketOrder 判断是否为篮子订单
func (o *Order) IsBasketOrder() bool {
	return len(o.ChildOrders) > 0
}

// GetTotalChildWeight 获取所有子订单权重总和
func (o *Order) GetTotalChildWeight() float64 {
	total := 0.0
	for _, child := range o.ChildOrders {
		total += child.Weight
	}
	return total
}

// ValidationResult 验证结果
type ValidationResult struct {
	IsValid bool     `json:"isValid"`
	Errors  []string `json:"errors,omitempty"`
}

// AddError 添加错误信息
func (vr *ValidationResult) AddError(err string) {
	vr.IsValid = false
	vr.Errors = append(vr.Errors, err)
}

// ClientType 客户端类型
type ClientType string

const (
	ClientA ClientType = "A"
	ClientB ClientType = "B"
	ClientC ClientType = "C"
)

// ClientConfig 客户端配置
type ClientConfig struct {
	AllowedTypes              []OrderType           `json:"allowedTypes"`
	AllowedCurrencies         []string              `json:"allowedCurrencies"`
	DestinationRules          map[OrderType]string  `json:"destinationRules"`
	MinBasketNotionalAmount   *float64              `json:"minBasketNotionalAmount,omitempty"`
	MinChildNotionalAmount    *float64              `json:"minChildNotionalAmount,omitempty"`
	MaxParentNotionalAmount   *float64              `json:"maxParentNotionalAmount,omitempty"`
}

// OrderIDGenerator 订单ID生成器接口
type OrderIDGenerator interface {
	GenerateOrderID() string
	ValidateOrderIDFormat(orderID string) bool
}

// DefaultOrderIDGenerator 默认订单ID生成器
type DefaultOrderIDGenerator struct {
	counter int
}

// GenerateOrderID 生成订单ID
func (g *DefaultOrderIDGenerator) GenerateOrderID() string {
	g.counter++
	today := time.Now().Format("20060102")
	return fmt.Sprintf("QF-%s-%d", today, g.counter)
}

// ValidateOrderIDFormat 验证订单ID格式
func (g *DefaultOrderIDGenerator) ValidateOrderIDFormat(orderID string) bool {
	// QF-{TodaysDate}-{index} 格式验证
	pattern := `^QF-\d{8}-\d+$`
	matched, _ := regexp.MatchString(pattern, orderID)
	return matched
}